# -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 18:03:22 2018

@author: Allen
"""
import numpy as np
import matplotlib.pyplot as plt

# 准备数据
x = np.array( [ 1., 2., 3., 4., 5. ] )
y = np.array( [ 1., 3., 2., 3., 5. ] )

# 画出图像
plt.scatter( x, y )
plt.axis( [ 0, 6, 0, 6 ] )
plt.show()

# 根据公式，计算 a 和 b
a = 0.0
b = 0.0

numerator = 0.0
denominator = 0.0
# 计算x，y的平均值
x_mean = np.mean( x )
y_mean = np.mean( y )

for x_ele, y_ele in zip( x, y ):
    numerator += ( x_ele - x_mean ) * ( y_ele - y_mean )
    denominator += ( x_ele - x_mean ) ** 2
    
a = numerator / denominator
b = y_mean - a * x_mean

print( a, b )

y_hat = a * x + b

# 画图 查看
plt.scatter( x, y )
plt.plot( x, y_hat, color = "red" )
plt.axis( [ 0, 6, 0, 6 ] )
plt.show()

x_predict = 7
y_predict = a * x_predict + b
print( y_predict ) #输出 6.0

# 使用自己写的SimpleLinearRegression来做预测
from playML.SimpleLinearRegression import SimpleLinearRegression1

reg1 = SimpleLinearRegression1()

reg1.fit( x, y )

y_predict = reg1.predict( x )
print( y_predict )

# 画图 查看
plt.scatter( x, y )
plt.plot( x, y_predict, color = "red" )
plt.axis( [ 0, 6, 0, 6 ] )
plt.show()

## 比较两个简单线性回归的效率差异
from playML.SimpleLinearRegression import SimpleLinearRegression2
reg2 = SimpleLinearRegression2()

reg2.fit( x, y )

y_predict = reg1.predict( x )
print( y_predict )
# 画图 查看
plt.scatter( x, y )
plt.plot( x, y_predict, color = "red" )
plt.axis( [ 0, 6, 0, 6 ] )
plt.show()

'''
性能测试就不写了，总之，使用向量化运算，效率要大大大大大大大大的提高，
以后要使用numpy中的向量运算
'''







